package com.china.school;

import com.china.school.pojo.Todo;
import com.china.school.pojo.User;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CGLIBProxyTest {
    public static void main(String[] args) {

        //目标对象
        User target = new User();
        //创建增强对象
        Todo todo = new Todo();

        //创建构建器
        Enhancer enhancer = new Enhancer();
        //设置代码类
        enhancer.setSuperclass(User.class);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("Object"+ o.getClass());
                System.out.println("Method"+ method);
                System.out.println("Object[]"+ objects);
                System.out.println("MethodProxy"+ methodProxy);
                todo.before();
                //无论是jDK或者是cglib都需要设置目标对象，都需要执行下面这个相同的方法
                Object res = method.invoke(target, objects);
                todo.after();
                return res;
            }
        });
        //创建代理对象
        User user = (User)enhancer.create();
        user.eat();
    }
}
